﻿using XiangziProjectTemplete.Core.Common.Helper;
using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.IRepository.Base;
using XiangziProjectTemplete.Core.IRepository.UnitOfWork;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.IServices.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.Enums.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model.Enums.XiangziProjectTemplete.LESPublicCommon;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.PostParamModels.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model.Views;
using XiangziProjectTemplete.Core.Services.BASE;
using System;
using System.Threading.Tasks;

namespace XiangziProjectTemplete.Core.Services.XiangziProjectTemplete
{
    /// <summary>
    /// 缓存区库存汇总
    /// </summary>
    public class V_LES_BufferStockCollectService : BaseServices<V_LES_BufferStockCollect>, IV_LES_BufferStockCollectService
    {
        private readonly IBaseRepository<V_LES_BufferStockCollect> _dal;
        private readonly IBaseRepository<Base_Material> _dal_Material;
        private readonly IBaseRepository<Les_Mater_V_Station> _dal_Les_Mater_V_Station;
        private readonly IBaseRepository<Base_Station> _dal_Station;
        private readonly IBaseRepository<Les_PickInStockTask> _dal_PickInStockTask;
        private readonly IBaseRepository<Les_TaskPhase> _dal_TaskPhase;
        private readonly IBaseRepository<Base_CodeItems> _dal_CodeItems;

        public V_LES_BufferStockCollectService(
            IBaseRepository<Base_CodeItems> dal_CodeItems,
            IBaseRepository<Les_TaskPhase> dal_TaskPhase,
            IBaseRepository<Les_PickInStockTask> dal_PickInStockTask,
            IBaseRepository<V_LES_BufferStockCollect> dal, IBaseRepository<Base_Material> dal_Material
            , IBaseRepository<Les_Mater_V_Station> dal_Les_Mater_V_Station,
            IBaseRepository<Base_Station> dal_Station)
        {
            this._dal_CodeItems = dal_CodeItems;
            this._dal_TaskPhase = dal_TaskPhase;
            this._dal = dal;
            base.BaseDal = dal;
            this._dal_Material = dal_Material;
            this._dal_Les_Mater_V_Station = dal_Les_Mater_V_Station;
            this._dal_Station = dal_Station;
            this._dal_PickInStockTask = dal_PickInStockTask;
        }

        /// <summary>
        /// 分拣完成后入库
        /// </summary>
        /// <param name="param"></param>
        /// <param name="_base_MaterialServices"></param>
        /// <param name="_unitOfWork"></param>
        /// <param name="base_StationServices"></param>
        /// <param name="_user"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> InStoreForSortSuccess(InStorePostParam param,
           IBase_MaterialServices _base_MaterialServices, IUnitOfWork _unitOfWork,
           IBase_StationServices base_StationServices, IUser _user, IBase_CodeItemsServices base_CodeItemsServices
            , ILes_PickInStockTaskServices _Les_PickInStockTaskServices,
           ILes_Mater_V_StationServices _les_Mater_V_StationServices,
           ILes_AgvTaskServices les_AgvTaskServices
          )
        {
            MessageModel<string> result = new MessageModel<string>();
            try
            {
                var operationRemark = "工作号:" + param.BurdenWorkNo + ",物料:" + param.MaterialCodeItemId + "入库。";
                _unitOfWork.BeginTran();//开启事务



                //保存物料信息
                Base_Material material = new Base_Material();

                material.MaterialCodeItemId = param.MaterialCodeItemId;
                var codeItem_Material = await base_CodeItemsServices.QueryById(param.MaterialCodeItemId);
                if (codeItem_Material == null)
                {
                    result = MessageModel<string>.Fail("没有找到物料码表项值为'" + param.MaterialCodeItemId + "'的物料");
                    return result;
                }
                material.MaterialName = codeItem_Material.name;
                material.MaterialCode = codeItem_Material.code;

                material.AllowProcedure = param.AllowProcedure;
                material.CargoNum = param.CargoNum;
                material.CargoType = param.CargoType;
                material.CargoTypeName = EnumberHelper.GetEnumObject<CargoTypeEnum>(param.CargoType.ToString()).ToString();
                //暂时先写死，都为 普通物料
                material.MaterialClassify = Convert.ToInt32(MaterialClassifyEnum.普通物料);
                material.MaterialClassifyName = MaterialClassifyEnum.普通物料.ToString();

                material.CargoWeight = param.CargoWeight;

                material.Id = Guid.NewGuid().ToString();
                material.CreateTime = material.ModifyTime = DateTime.Now;
                material.CreateBy = material.ModifyBy = _user.Name;
                material.CreateId = material.ModifyId = _user.ID;
                material.InStoreTime = DateTime.Now;
                material.OperationRemark = operationRemark + "新增物料";

                material.BurdenWorkNo = param.BurdenWorkNo;//配料任务号


                await _dal_Material.Add(material);

                //存放的库位
                var saveStation = await base_StationServices.QueryById(param.StationId);
                if (saveStation == null)
                {
                    result = MessageModel<string>.Fail("指定的站点不存在！");
                    return result;
                }
                if (saveStation.IsLock == 1)
                {
                    result = MessageModel<string>.Fail("指定的站点'" + saveStation.StationName + "'已经被锁定！");
                    return result;
                }
                if (saveStation.IsFull == 1)
                {
                    result = MessageModel<string>.Fail("指定的站点'" + saveStation.StationName + "'已经有货！");
                    return result;
                }
                //验证选中的库位是否跟 IsPersonPickInStore一致
                Base_CodeItems storeAreaCodeItem = await _dal_CodeItems.QueryById(Convert.ToInt32(saveStation.StoreArea));
                if (storeAreaCodeItem == null)
                {
                    result = MessageModel<string>.Fail("指定的站点'" + saveStation.StationName + "'没有在码表中找到区域信息！");
                    return result;
                }
                if (storeAreaCodeItem.code == StoreAreaEnum.FJQ.ToString() && param.IsPersonPickInStore)
                {
                    result = MessageModel<string>.Fail("指定的站点'" + saveStation.StationName + "'属于" + EnumberHelper.GetEnumDescription(StoreAreaEnum.FJQ) + "，不允许人工入库！");
                    return result;
                }
                if (storeAreaCodeItem.code == StoreAreaEnum.StoreBuffer.ToString() && !param.IsPersonPickInStore)
                {
                    result = MessageModel<string>.Fail("指定的站点'" + saveStation.StationName + "'属于" + EnumberHelper.GetEnumDescription(StoreAreaEnum.StoreBuffer) + "，必须是人工入库！");
                    return result;
                }


                //修改库位状态
                saveStation.IsFull = 1;
                //toStation.IsLock = 1;//不需要锁定库位！
                saveStation.ModifyBy = _user.Name;
                saveStation.ModifyTime = DateTime.Now;
                saveStation.OperationRemark = operationRemark + "修改为库存有货";
                await _dal_Station.Update(saveStation);

                //绑定库位
                //验证如果存在该站点的数据，则报警
                var resultMvs = await _les_Mater_V_StationServices.GetLes_Mater_V_StationByStationId(saveStation.Id);
                if (resultMvs.success)
                {
                    if (resultMvs.response != null)
                    {
                        result = MessageModel<string>.Fail("已经存在站点'" + saveStation.StationName + "'的库位绑定信息，请联系管理员！");
                        return result;
                    }
                }
                else
                {
                    result = MessageModel<string>.Fail(resultMvs.msg);
                    return result;
                }

                M_V_S_StateEnum mvsState = M_V_S_StateEnum.在库分拣区料;
                Les_Mater_V_Station les_Mater_V_Station = new Les_Mater_V_Station()
                {
                    Id = Guid.NewGuid().ToString(),
                    StationId = saveStation.Id,
                    StationCode = saveStation.StationCode,
                    MaterialId = material.Id,
                    MaterialName = material.MaterialName,
                    CreateTime = DateTime.Now,
                    ModifyTime = DateTime.Now,
                    CreateBy = _user.Name,
                    ModifyBy = _user.Name,
                    OperationRemark = operationRemark + "绑定库位",
                    State = Convert.ToInt32(mvsState),
                    StateName = mvsState.ToString()
                };
                await _dal_Les_Mater_V_Station.Add(les_Mater_V_Station);


                //保存 分拣入库表
                var pickInStockTaskNo = TaskNoHelper.GenerateLesTaskNo("PICK");
                Les_PickInStockTask les_PickInStockTask = ClassHelper.RotationMapping<Les_PickInStockTask, InStorePostParam>(param);
                les_PickInStockTask.Id = Guid.NewGuid().ToString();
                les_PickInStockTask.PickInStockTaskNo = pickInStockTaskNo;
                les_PickInStockTask.MaterialId = material.Id;

                les_PickInStockTask.CreateId = _user.ID;
                les_PickInStockTask.CreateBy = _user.Name;
                les_PickInStockTask.CreateTime = DateTime.Now;
                les_PickInStockTask.ModifyId = _user.ID;
                les_PickInStockTask.ModifyBy = _user.Name;
                les_PickInStockTask.ModifyTime = DateTime.Now;

                les_PickInStockTask.IsPersonPickInStore = param.IsPersonPickInStore;
                LesTaskStatusEnum lesTaskStatusEnum = LesTaskStatusEnum.新建任务;
                if (param.IsPersonPickInStore)
                {
                    //验证这个站点是否被AGV任务占用
                    MessageModel<bool> validateIsUsingAgvTaskForStation=await les_AgvTaskServices.ValidateIsUsingAgvTaskForStation(saveStation);
                    if (validateIsUsingAgvTaskForStation.success == false) {
                        result = MessageModel<string>.Fail(validateIsUsingAgvTaskForStation.msg);
                        return result;
                    }

                    lesTaskStatusEnum = LesTaskStatusEnum.已完成;
                    les_PickInStockTask.InStockDate = les_PickInStockTask.TaskFinishTime = DateTime.Now;

                    //修改分拣点为空，赋值缓存点
                    les_PickInStockTask.StationId = 0;
                    les_PickInStockTask.ToStationId = param.StationId;
                }
                les_PickInStockTask.LesTaskStatus = Convert.ToInt32(lesTaskStatusEnum);
                les_PickInStockTask.LesTaskStatusName = Convert.ToString(lesTaskStatusEnum);
                //保存物料
                les_PickInStockTask.MaterialCode = codeItem_Material.code;
                les_PickInStockTask.MaterialName = codeItem_Material.name;
                les_PickInStockTask.MaterialClassify = material.MaterialClassify;
                les_PickInStockTask.MaterialClassifyName = EnumberHelper.GetEnumObject<MaterialClassifyEnum>(param.MaterialClassify.ToString()).ToString();
                les_PickInStockTask.CargoType = param.CargoType;
                les_PickInStockTask.CargoTypeName = EnumberHelper.GetEnumObject<CargoTypeEnum>(param.CargoType.ToString()).ToString();

                await _dal_PickInStockTask.AddEntity(les_PickInStockTask);

                await _Les_PickInStockTaskServices.UpdateIsPickFinishByBurdenWorkNo(les_PickInStockTask.IsPickFinish, les_PickInStockTask, _user, true);

                //更新 所有本配料任务号和物料号的 的备注
                await _Les_PickInStockTaskServices.UpdateRemarkByBurdenWorkNo(les_PickInStockTask.Remark, les_PickInStockTask, _user, true);

                //保存 XiangziProjectTemplete任务阶段表
                Les_TaskPhase les_TaskPhase = new Les_TaskPhase();
                les_TaskPhase.Id = Guid.NewGuid().ToString();
                les_TaskPhase.CreateId = _user.ID;
                les_TaskPhase.CreateBy = _user.Name;
                les_TaskPhase.CreateTime = DateTime.Now;
                les_TaskPhase.LesTaskId = les_PickInStockTask.Id;
                les_TaskPhase.LesTaskNo = pickInStockTaskNo;
                les_TaskPhase.TaskType = Convert.ToInt32(AGVTaskType.分拣入库);
                les_TaskPhase.TaskTypeName = Convert.ToString(AGVTaskType.分拣入库);

                les_TaskPhase.LesTaskStatus = Convert.ToInt32(lesTaskStatusEnum);
                les_TaskPhase.LesTaskStatusName = Convert.ToString(lesTaskStatusEnum);
                if (param.IsPersonPickInStore)
                {
                    les_TaskPhase.OperationRemark = "人工分拣入库";
                }
                else
                {
                    les_TaskPhase.OperationRemark = "新建分拣入库任务";
                }

                await _dal_TaskPhase.Add(les_TaskPhase);

                result = MessageModel<string>.Success("成功",les_PickInStockTask.PickInStockTaskNo);
            }
            catch (System.Exception)
            {
                throw;
            }
            finally
            {
                if (result.success)
                    _unitOfWork.CommitTran();
                else
                    _unitOfWork.RollbackTran();
            }

            return result;
        }
    }
}
